package com.xgkj.diyiketang.yizhibo;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.PowerManager;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.easyvaas.sdk.live.base.EVStreamerParameter;
import com.easyvaas.sdk.live.base.view.CameraPreview;
import com.easyvaas.sdk.live.wrapper.EVLive;
import com.easyvaas.sdk.live.wrapper.LiveConstants;
import com.xgkj.diyiketang.EatShowApp;
import com.xgkj.diyiketang.R;
import com.xgkj.diyiketang.activity.BangDingPhoneActivity;
import com.xgkj.diyiketang.activity.BaseActivity;
import com.xgkj.diyiketang.activity.ChooseRecommImgActivity;
import com.xgkj.diyiketang.activity.TuiJianTitle;
import com.xgkj.diyiketang.activity.YuZhiBoActivity;
import com.xgkj.diyiketang.http.engine.ShowToastTaskEventListener;
import com.xgkj.diyiketang.http.engine.TaskEventListener;
import com.xgkj.diyiketang.task.IsHaveLiveCoverTask;
import com.xgkj.diyiketang.task.StartLiveTask;
import com.xgkj.diyiketang.task.UploadImage;
import com.xgkj.diyiketang.util.DateTimePickDialogUtil;
import com.xgkj.diyiketang.util.DialogUtil;
import com.xgkj.diyiketang.util.EatShowSetting;
import com.xgkj.diyiketang.util.GetImagePathUtil;
import com.xgkj.diyiketang.util.ImageCache;
import com.xgkj.diyiketang.util.PalLog;
import com.xgkj.diyiketang.util.ToastUtil;
import com.xgkj.diyiketang.util.ViewUtil;
import com.xgkj.diyiketang.weidget.ClearableEditText;
import com.xgkj.diyiketang.weidget.MoneyInputEditText;
import com.xgkj.diyiketang.weidget.NestRadioGroup;
import com.xgkj.diyiketang.yizhibo.been.LiveOption;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

public class ZhiboSettingActivity extends BaseActivity implements View.OnClickListener, NestRadioGroup.OnCheckedChangeListener {
    private Context mContext;
//    private YZBSdk mYZBSdk;
    static final int RESULT_CODE_TITLE = 111;
    private Button mLivePrepareBtn;
    private RelativeLayout mFengMianLayout;
    InputMethodManager im;
    private PopupWindow popWindow;
    private static final int CAMERA_REQUEST = 0;
    private static final int CHOOSE_REQUEST = 11;
    private static final int CROP_REQUEST = 2;
    private static final int CHOOSE_IMG_REQUEST = 3;
    private File mFile;
    private String local_url;
    private static final String CAMERA_FILE = "chibo/img";
    private int uploadImageTaskId = -1;
    private String headLogo;
    private String imageId;
    private ImageView mFengmianBg;
    private TextView uploadImgText;
    private ImageView updateImg;
    private TextView mTitleText;
    private String titleString;
    private int ishavecoverTaskId = -1;
    private String coverUrl;
    private ImageView closeBtn;
    private String mYzbUserId;
    private String mBusinessId = null;
    private RadioButton free;
    private RadioButton charge;
    private RadioButton password;
    private LinearLayout chargeLayout;
    private MoneyInputEditText chargeEdit;
    private LinearLayout pwdLayout;
    private ClearableEditText passwordEdit;
    private CheckBox isOpenCheck;
    private NestRadioGroup liveTypeGroup;
    private int mCheckId;
    private int liveType;
    private String charge_amount;
    private String live_pwd;
    private int liveIsOpen;
    private ImageView lineDivider;
    private RelativeLayout mStartLayout;
    private EditText mStartTime;
    private String from;
    private Button yuyueBtn;
    private String initDateTime = "2016年05月12日 11:00"; //= "2016年4月29日 11:00"; // 初始化开始时间
    SimpleDateFormat df;
    private String mKaishiTime;
    private EditText descEdit;
    private String descString;
    private int yuyueLiveTaskId = -1;
    private PopupWindow boPopWindow;
    private PopupWindow stopPopWindow;
    private RelativeLayout liveCateLayout;
    private TextView liveCateText;
    private String liveCateString;
    private InputMethodManager inputMethodManager;
    private NestRadioGroup liveVipTypeGroup;
    private RadioButton vip1;
    private RadioButton vip2;
    private RadioButton vip3;
    private RadioButton vip4;
    private RadioButton vip5;
    private Button titleMoreBtn;
    private int mFans;
    private View vipLevelLayout;
    private String url;
    private TextView start_time_text;
    private CameraPreview cameraPreview;
    private PowerManager.WakeLock mWakeLock;
    private LiveOption mliveOption;
    private EVLive mEVLive;
    private FrameLayout mCameraViewFrame;
    private RelativeLayout zhibo_ll;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.yuzhibo);
        mContext = this;
        im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        checkAppKey(Constants.APP_KEY_ID);

        File folder = EatShowSetting.getInstance(mContext).getDataFolder(CAMERA_FILE);
        String fileName = "IMG" + System.currentTimeMillis() + ".jpeg";
        mFile = new File(folder, fileName);
        df = new SimpleDateFormat("yyyy年MM月dd日 HH:mm");//设置日期格式
        inputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
        initUIComponents();
//        mEVLive = new EVLive(ZhiboSettingActivity.this);
//        EVStreamerParameter.Builder builder = new EVStreamerParameter.Builder();
////        if (mliveOption != null) {
//        builder.setVideoResolution(LiveConstants.VIDEO_RESOLUTION_360P)
//                .setInitVideoBitrate(500)
//                .setAudioBitrate(LiveConstants.AUDIO_BITRATE_32K)
//                .setAudioCodec(LiveConstants.AUDIO_CODEC_AAC_LC)
//                .setUseFrontCamera(true)
//                .setIsBeautyOn(false)
//                .setPortrait(true);
////                    .setDisplayRotation(mliveOption.isPortrait() ? 90 : 0);
////        }
//        mEVLive.setParameter(builder.build());
////        mEVLive.setCameraPreview(cameraPreview);
//        mEVLive.onCreate();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.fengmian_layout:
                im.hideSoftInputFromWindow(ZhiboSettingActivity.this.getCurrentFocus().getWindowToken(), 0);
                popWindow.showAtLocation(v, Gravity.BOTTOM, 0, 0);
                break;

            case R.id.takephoto:
                popWindow.dismiss();
                Intent camera_intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                camera_intent
                        .putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mFile));
                startActivityForResult(camera_intent, CAMERA_REQUEST);
                break;
            case R.id.choosephoto:
                popWindow.dismiss();
//                Intent intent = new Intent(mContext, PhoneMainActivity.class);
//                startActivityForResult(intent,300);
                Intent choose_intent = new Intent();
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                    choose_intent.setAction(Intent.ACTION_OPEN_DOCUMENT);
                } else {
                    choose_intent.setAction(Intent.ACTION_GET_CONTENT);
                }
                choose_intent.setType("image/*");
                startActivityForResult(choose_intent, CHOOSE_REQUEST);
                break;
            case R.id.choose_recommend_photo:
                popWindow.dismiss();
                Intent choose_img_intent = new Intent(ZhiboSettingActivity.this, ChooseRecommImgActivity.class);
                startActivityForResult(choose_img_intent, CHOOSE_IMG_REQUEST);
                break;
            case R.id.live_prepare_btn:
                if (checkInput()) {
//                    startActivityForResult(new Intent(getApplicationContext(), RecorderActivity.class),
//                        REQUEST_CODE_RECORDER);
                    checkPhoneNum();

                }
//                stopPopwindow();
                break;
            case R.id.close_btn:
                finish();
                break;
            case R.id.cancle:
                popWindow.dismiss();
                break;

            case R.id.yuyue_btn:
                if (checkInput()) {
                    doYuYue();
                }
                break;
            case R.id.title_more:
                startActivityForResult(new Intent(ZhiboSettingActivity.this, TuiJianTitle.class), RESULT_CODE_TITLE);
                break;
            case R.id.starttime_layout:
                initDateTime = df.format(new Date());
                DateTimePickDialogUtil dateTimePicKDialog = new DateTimePickDialogUtil(
                        ZhiboSettingActivity.this, initDateTime);
                dateTimePicKDialog.dateTimePicKDialog(mStartTime);

                break;

            case R.id.leibie_layout:
                try {
                    inputMethodManager.hideSoftInputFromWindow(ZhiboSettingActivity.this.getCurrentFocus().getWindowToken(), 0);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                boPopWindow.showAtLocation(v, Gravity.BOTTOM, 0, 0);
                break;
            case R.id.beautiful_teacher:
                liveCateText.setText("最美教师");
                liveCateString = "992a1f76047e4839a9631259c033d867";
                boPopWindow.dismiss();
                break;
            case R.id.youer:
                liveCateText.setText("家长专区");
                liveCateString = "31d41764f6a24099a04bc1b614289f2c";
                boPopWindow.dismiss();
                break;

            case R.id.k12:
                liveCateText.setText("今日课表");
                liveCateString = "a10e3a144fd6412598c18796951386c1";
                boPopWindow.dismiss();
                break;
            case R.id.techang:
                liveCateText.setText("每日精彩");
                liveCateString = "d74604615a344df3bb4c569a40e16d28";
                boPopWindow.dismiss();
                break;
            case R.id.jiatingjiaoyu:
                liveCateText.setText("本周总结");
                liveCateString = "e9fa420b2d774965b80b48727fe3e968";
                boPopWindow.dismiss();
                break;
            case R.id.naolijiaoyu:
                liveCateText.setText("校长推荐");
                liveCateString = "fe45e51fee0f4d43998490cb675a9fa4";
                boPopWindow.dismiss();
                break;

        }
    }
    private void stopPopwindow() {
        View view = LayoutInflater.from(mContext).inflate(R.layout.zhibo_stop_pop, null);
        ImageView viewById = (ImageView) view.findViewById(R.id.zhibostop_zhubo_img);
        TextView danmu_num = (TextView) view.findViewById(R.id.zhibostop_danmu_num);
        TextView person_num = (TextView) view.findViewById(R.id.zhibostop_person_num);
        TextView redflower_num = (TextView) view.findViewById(R.id.zhibostop_redflower_num);
        TextView zhibo_stop_time = (TextView) view.findViewById(R.id.zhibostop_time);
        ((ImageView) view.findViewById(R.id.zhibostop_weixin))
                .setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                    }
                });
        ((ImageView) view.findViewById(R.id.zhibostop_friend_circle))
                .setOnClickListener(this);
//        ((ImageView) view.findViewById(R.id.zhibostop_weibo))
//                .setOnClickListener(this);
        ((ImageView) view.findViewById(R.id.zhibostop_qq))
                .setOnClickListener(this);
        ((ImageView) view.findViewById(R.id.zhibostop_zone))
                .setOnClickListener(this);
        stopPopWindow = new PopupWindow(view, WindowManager.LayoutParams.FILL_PARENT, WindowManager.LayoutParams.FILL_PARENT,true);
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = 0.5f; //0.0-1.0
        getWindow().setAttributes(lp);
        ColorDrawable dw = new ColorDrawable(0x60000000);
        stopPopWindow.setBackgroundDrawable(dw);
        stopPopWindow.showAtLocation(zhibo_ll,Gravity.CENTER,0,0);
        stopPopWindow.setFocusable(true);
//        popWindow.setOutsideTouchable(true);
    }
    private void doYuYue() {
        StartLiveTask task = new StartLiveTask("", "", imageId, titleString, liveIsOpen, liveType, charge_amount, live_pwd, 0, mKaishiTime, liveCateString, descString,"1");
        task.addListener(uploadImageListener);
        yuyueLiveTaskId = getEatShowApp().getTaskManager().addTask(task);
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
//        if (null != mEVLive) {
//            mEVLive.onDestroy();
//        }
    }
    private void checkPhoneNum() {
//        if (mEVLive != null) {
//            mEVLive.stopLive();
//        }
//        setResult(RESULT_OK);
        String phoneNum = EatShowApp.getInstance().getmUserInfo().getPhoneNum();
        if (ViewUtil.isNull(phoneNum)) {
            Intent bdIntent = new Intent(mContext, BangDingPhoneActivity.class);
            startActivity(bdIntent);
        } else {
            Intent intent = new Intent(getApplicationContext(), RecorderNewActivity.class);
            intent.putExtra("FENGMIANID", imageId);
            intent.putExtra("TITLE", titleString);
            intent.putExtra("YZBUSERID", mYzbUserId);
            intent.putExtra("IS_OPEN", liveIsOpen);
            intent.putExtra("LIVE_TYPE", liveType);
            intent.putExtra("DESC", descString);
            intent.putExtra("LIVECATE", liveCateString);
            if (liveType == 1) {
                intent.putExtra("AMOUNT", charge_amount);
            } else if (liveType == 2) {
                intent.putExtra("PWD", live_pwd);
            }

            if (mBusinessId != null) {
                intent.putExtra("BUSINESSID", mBusinessId);
            }
            startActivity(intent);
            finish();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
    private void initUIComponents() {
        mLivePrepareBtn = (Button) findViewById(R.id.live_prepare_btn);
        mLivePrepareBtn.setOnClickListener(this);
        mCameraViewFrame = (FrameLayout) findViewById(R.id.zhibo_camera_preview_fl);
        mCameraViewFrame.setVisibility(View.VISIBLE);
        cameraPreview = (CameraPreview) findViewById(R.id.zhibo_camera_preview);
        mFengMianLayout = (RelativeLayout) findViewById(R.id.fengmian_layout);
        mFengMianLayout.setOnClickListener(this);
        zhibo_ll = (RelativeLayout)findViewById(R.id.zhibo_setting_ll);
        mFengmianBg = (ImageView) findViewById(R.id.fengmian_bg);
        updateImg = (ImageView) findViewById(R.id.upload_fengmian);
        uploadImgText = (TextView) findViewById(R.id.fengmian_text);
        mTitleText = (TextView) findViewById(R.id.hd_title);
        closeBtn = (ImageView) findViewById(R.id.close_btn);
        closeBtn.setOnClickListener(this);
        free = (RadioButton) findViewById(R.id.free);
        charge = (RadioButton) findViewById(R.id.charge);
        password = (RadioButton) findViewById(R.id.password);
        vip1 = (RadioButton) findViewById(R.id.vip1);
        vip2 = (RadioButton) findViewById(R.id.vip2);
        vip3 = (RadioButton) findViewById(R.id.vip3);
        vip4 = (RadioButton) findViewById(R.id.vip4);
        vip5 = (RadioButton) findViewById(R.id.vip5);
        chargeLayout = (LinearLayout) findViewById(R.id.charge_layout);
        chargeEdit = (MoneyInputEditText) findViewById(R.id.charge_edit);
        chargeEdit.setNumberStyle(true);
        pwdLayout = (LinearLayout) findViewById(R.id.pwd_layout);
        passwordEdit = (ClearableEditText) findViewById(R.id.password_edit);
        isOpenCheck = (CheckBox) findViewById(R.id.isopen_check);
        liveTypeGroup = (NestRadioGroup) findViewById(R.id.live_type_group);
//        liveVipTypeGroup = (NestRadioGroup) findViewById(R.id.live_vip_type_group);
        liveTypeGroup.setOnCheckedChangeListener(this);
//        liveVipTypeGroup.setOnCheckedChangeListener(this);
        lineDivider = (ImageView) findViewById(R.id.line_divider);
        free.setChecked(true);
        descEdit = (EditText) findViewById(R.id.hd_desc);
        mStartLayout = (RelativeLayout) findViewById(R.id.starttime_layout);
        mStartTime = (EditText) findViewById(R.id.starttime_content);
        start_time_text = (TextView) findViewById(R.id.start_time_text);
        mStartLayout.setOnClickListener(this);
        yuyueBtn = (Button) findViewById(R.id.yuyue_btn);
        titleMoreBtn = ((Button) findViewById(R.id.title_more));
        titleMoreBtn.setOnClickListener(this);
//        vipLevelLayout = ((LinearLayout) findViewById(R.id.vip_level_layout));
        Intent intent = getIntent();
        if (intent != null) {
            mBusinessId = intent.getStringExtra("BUSINESSID");
            from = intent.getStringExtra("FROM");
            mFans = intent.getIntExtra("FANSNUM", 0);

            if (!ViewUtil.isNull(from) && from.equals("ZHIBO")) {
                mStartLayout.setVisibility(View.GONE);
                mLivePrepareBtn.setVisibility(View.VISIBLE);
                yuyueBtn.setVisibility(View.GONE);
            } else {
                mStartLayout.setVisibility(View.VISIBLE);
                mLivePrepareBtn.setVisibility(View.GONE);
                yuyueBtn.setVisibility(View.VISIBLE);
                yuyueBtn.setOnClickListener(this);
            }
            if (mFans >= 0 && mFans < 200) {
                vip1.setVisibility(View.GONE);
                vip2.setVisibility(View.GONE);
                vip3.setVisibility(View.GONE);
                vip4.setVisibility(View.GONE);
                vip5.setVisibility(View.GONE);
            } else if (mFans >= 200 && mFans < 400) {
                vip1.setVisibility(View.VISIBLE);
                vip2.setVisibility(View.GONE);
                vip3.setVisibility(View.GONE);
                vip4.setVisibility(View.GONE);
                vip5.setVisibility(View.GONE);
            } else if (mFans >= 400 && mFans < 600) {
                vip1.setVisibility(View.VISIBLE);
                vip2.setVisibility(View.VISIBLE);
                vip3.setVisibility(View.GONE);
                vip4.setVisibility(View.GONE);
                vip5.setVisibility(View.GONE);
            } else if (mFans >= 600 && mFans < 800) {
                vip1.setVisibility(View.VISIBLE);
                vip2.setVisibility(View.VISIBLE);
                vip3.setVisibility(View.VISIBLE);
                vip4.setVisibility(View.GONE);
                vip5.setVisibility(View.GONE);
            } else if (mFans >= 800 && mFans < 1000) {
                vip1.setVisibility(View.VISIBLE);
                vip2.setVisibility(View.VISIBLE);
                vip3.setVisibility(View.VISIBLE);
                vip4.setVisibility(View.VISIBLE);
                vip5.setVisibility(View.GONE);
            } else if (mFans >= 1000) {
                vip1.setVisibility(View.VISIBLE);
                vip2.setVisibility(View.VISIBLE);
                vip3.setVisibility(View.VISIBLE);
                vip4.setVisibility(View.VISIBLE);
                vip5.setVisibility(View.VISIBLE);
            }
        }

        liveCateLayout = (RelativeLayout) findViewById(R.id.leibie_layout);
        liveCateLayout.setOnClickListener(this);
        liveCateText = (TextView) findViewById(R.id.leibie_content);
        initBOPopWindow();
        doIsHaveLiveCover();
        initPopWindow();
        //mPlayBtn = (Button) findViewById(R.id.play_btn);
//        mListView = (ListView) findViewById(R.id.video_list);

    }

    private void initPopWindow() {
        View view = LayoutInflater.from(mContext).inflate(R.layout.popwindow,
                null);
        ((Button) view.findViewById(R.id.takephoto)).setOnClickListener(this);
        ((Button) view.findViewById(R.id.choosephoto)).setOnClickListener(this);
        ((Button) view.findViewById(R.id.choose_recommend_photo)).setOnClickListener(this);
        ((Button) view.findViewById(R.id.cancle)).setOnClickListener(this);
        popWindow = new PopupWindow(view, LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);
        popWindow.setBackgroundDrawable(new ColorDrawable());
        popWindow.setFocusable(true);
        popWindow.setOutsideTouchable(true);
    }


    private void initBOPopWindow() {
        View view = LayoutInflater.from(mContext).inflate(R.layout.pop_leibie, null);
        view.findViewById(R.id.beautiful_teacher).setOnClickListener(this);
        view.findViewById(R.id.youer).setOnClickListener(this);
        view.findViewById(R.id.k12).setOnClickListener(this);
        view.findViewById(R.id.techang).setOnClickListener(this);
        view.findViewById(R.id.jiatingjiaoyu).setOnClickListener(this);
        view.findViewById(R.id.naolijiaoyu).setOnClickListener(this);
        boPopWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        boPopWindow.setBackgroundDrawable(new ColorDrawable());
        boPopWindow.setFocusable(true);
        boPopWindow.setOutsideTouchable(true);
    }

    private boolean checkInput() {
        titleString = mTitleText.getText().toString();
        mKaishiTime = mStartTime.getText().toString();
        descString = descEdit.getText().toString();
        if (mFengmianBg.getDrawable() == null) {
            Toast.makeText(mContext, "请上传您的直播封面", Toast.LENGTH_SHORT)
                    .show();
            return false;
        }
        if (TextUtils.isEmpty(titleString)) {
            Toast.makeText(mContext, "请输入直播标题", Toast.LENGTH_SHORT)
                    .show();
            return false;
        }

        if (TextUtils.isEmpty(descString)) {
            Toast.makeText(mContext, "请输入直播内容介绍", Toast.LENGTH_SHORT)
                    .show();
            return false;
        }


        if (isOpenCheck.isChecked()) {
            liveIsOpen = 1;
        } else {
            liveIsOpen = 0;
        }

        if (liveType == 1) {
            charge_amount = chargeEdit.getText().toString();
            if (ViewUtil.isNull(charge_amount)) {
                Toast.makeText(mContext, R.string.charge_amount_null, Toast.LENGTH_SHORT).show();
                return false;
            }
            double amount_double = 0;

            try {
                amount_double = Double.parseDouble(charge_amount);
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }
            if (amount_double <= 0) {
                Toast.makeText(mContext, R.string.charge_amount_null, Toast.LENGTH_SHORT).show();
                return false;
            }

        } else if (liveType == 2) {
            live_pwd = passwordEdit.getText().toString();
            if (ViewUtil.isNull(live_pwd)) {
                Toast.makeText(mContext, R.string.no_psw, Toast.LENGTH_SHORT).show();
                return false;
            }
        }
        if (!ViewUtil.isNull(from) && from.equals("YUYUE")) {
            if (TextUtils.isEmpty(mKaishiTime)) {
                Toast.makeText(mContext, "请先选择开始时间", Toast.LENGTH_SHORT).show();
                return false;
            }
        }

        return true;
    }

    private void checkAppKey(String appkey) {
        String cachedAppKey = Preferences.getInstance(getApplicationContext()).getString(Preferences.KEY_APP_KEY);
        if (TextUtils.isEmpty(cachedAppKey) || !cachedAppKey.equals(appkey)) {
            Preferences.getInstance(getApplicationContext()).putString(Preferences.KEY_APP_KEY, appkey);
            Preferences.getInstance(getApplicationContext()).remove(Preferences.KEY_SESSION_ID);
            Preferences.getInstance(getApplicationContext()).remove(Preferences.KEY_USER_NUMBER);
            Preferences.getInstance(getApplicationContext()).remove(Preferences.KEY_USER_NICKNAME);
        }
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case CAMERA_REQUEST:
                if (!mFile.exists()) {
                    return;
                }
                Uri uri = Uri.fromFile(mFile);
                startPhotoZoom(uri);
//                uploadImage(mFile.getAbsolutePath());
                break;

            case CHOOSE_REQUEST:
                if (resultCode != RESULT_OK) {
                    return;
                }
                if (data == null)
                    return;
                Uri choose_uri = data.getData();
                startPhotoZoom(choose_uri);
                break;
            case CHOOSE_IMG_REQUEST:
                if (resultCode == 2) {
                    url = data.getStringExtra("Url");
                    imageId = data.getStringExtra("iamgeUrl");
                    if (url != null && url.length() > 0) {
                        ImageCache.getInstance(mContext).loadBitmapToView(mFengmianBg, url, new ViewUtil.Size(ViewUtil.dip2px(mContext, 200), ViewUtil.dip2px(mContext, 200)));
                        //mFengMianLayout.setOnClickListener(null);
                        mFengmianBg.setVisibility(View.VISIBLE);
                        uploadImgText.setVisibility(View.GONE);
                        updateImg.setVisibility(View.GONE);
                    }
                }
                break;
            case CROP_REQUEST:
                if (resultCode != RESULT_OK) {
                    return;
                }
                if (data == null)
                    return;
                if (!mFile.exists()) {
                    return;
                }
                uploadImage(mFile.getAbsolutePath());
                break;

            case 300:
                PalLog.e("返回resultcode", resultCode + "");
                break;

            default:
                break;
        }
        if (RESULT_CODE_TITLE == resultCode && data != null) {
            setResult(RESULT_OK, data);
            Bundle bundle = data.getBundleExtra("bundle");
            String title = bundle.getString("TITLE");
            if (null != title) {
                mTitleText.setText(title);
            }
        }
    }

    //上传图片
    private void uploadImage(String path) {
        UploadImage task = new UploadImage(path);
        task.addListener(uploadImageListener);
        uploadImageTaskId = getEatShowApp().getTaskManager().addTask(task);
    }

    //获取直播封面
    private void doIsHaveLiveCover() {
        IsHaveLiveCoverTask coverTask = new IsHaveLiveCoverTask();
        coverTask.addListener(uploadImageListener);
        ishavecoverTaskId = getEatShowApp().getTaskManager().addTask(coverTask);
    }

    private int isLiveButton;
    private TaskEventListener uploadImageListener = new ShowToastTaskEventListener(this) {
        @Override
        public void handleTaskCompleted(int taskId, int result, Object data) {
            super.handleTaskCompleted(taskId, result, data);
            if (taskId == uploadImageTaskId) {
                uploadImageTaskId = -1;
                if (data != null) {
                    JSONObject json = (JSONObject) data;
                    headLogo = json.getString("imageURL");
                    if (headLogo != null && headLogo.length() > 0) {
                        mFengmianBg.setVisibility(View.VISIBLE);
                        uploadImgText.setVisibility(View.GONE);
                        updateImg.setVisibility(View.GONE);
                        ImageCache.getInstance(mContext).loadBitmapToView(mFengmianBg, headLogo, new ViewUtil.Size(ViewUtil.dip2px(mContext, 200), ViewUtil.dip2px(mContext, 200)));
                    }
                    imageId = json.getString("imageId");
                }
                if (mFile.exists()) {
                    mFile.delete();
                }
            } else if (taskId == ishavecoverTaskId) {
                JSONObject json = (JSONObject) data;
                coverUrl = json.getString("liveCoverUrl");
                mYzbUserId = json.getString("yiUserId");
                isLiveButton = json.getIntValue("isLiveButton");
                if (coverUrl != null && coverUrl.length() > 0) {
                    ImageCache.getInstance(mContext).loadBitmapToView(mFengmianBg, coverUrl, new ViewUtil.Size(ViewUtil.dip2px(mContext, 200), ViewUtil.dip2px(mContext, 200)));
                    //mFengMianLayout.setOnClickListener(null);
                    mFengmianBg.setVisibility(View.VISIBLE);
                    uploadImgText.setVisibility(View.GONE);
                    updateImg.setVisibility(View.GONE);
                }
                imageId = json.getString("imageId");
                titleString = json.getString("liveTitle");
                if (isLiveButton == 1) {
                    DialogUtil.createDialog(mContext, -1, getString(R.string.prompt), "您是否继续上次的直播", getString(R.string.ok), getString(R.string.cancel), new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            Intent intent = new Intent(getApplicationContext(), RecorderNewActivity.class);
                            intent.putExtra("YZBUSERID", mYzbUserId);
                            intent.putExtra("isXubo", 1);
                            intent.putExtra("TITLE", titleString);
                            startActivity(intent);
                            finish();
                        }
                    }, null);
                }
            } else if (taskId == yuyueLiveTaskId) {
                ToastUtil.showMessage(mContext, "预约直播成功！");
                finish();
            }
        }

        @Override
        public void handleTaskError(int taskId, int errorCode, String errorMsg) {
            super.handleTaskError(taskId, errorCode, errorMsg);

        }

        @Override
        public void handleTaskMessage(int taskId, Object data) {
            super.handleTaskMessage(taskId, data);
        }
    };


    public void startPhotoZoom(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            local_url = GetImagePathUtil.getPath(mContext, uri);
            uri = Uri.fromFile(new File(local_url));
        }
        intent.setDataAndType(uri, "image/*");
        // crop=true是设置在开启的Intent中设置显示的VIEW可裁剪
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 710);
        intent.putExtra("outputY", 710);
        intent.putExtra("scale", true);
        intent.putExtra("return-data", false);
        intent.putExtra("scale", true);//黑边
        intent.putExtra("scaleUpIfNeeded", true);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mFile));
        startActivityForResult(intent, CROP_REQUEST);
    }

    @Override
    public void onCheckedChanged(NestRadioGroup group, int checkedId) {
        if (checkedId == mCheckId) return;
        mCheckId = checkedId;
        switch (checkedId) {
            case R.id.free:
                liveType = 0;
                pwdLayout.setVisibility(View.GONE);
                chargeLayout.setVisibility(View.GONE);
                lineDivider.setVisibility(View.GONE);
                try {
                    im.hideSoftInputFromWindow(ZhiboSettingActivity.this.getCurrentFocus().getWindowToken(), 0);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;

            case R.id.charge:
                pwdLayout.setVisibility(View.GONE);
                lineDivider.setVisibility(View.VISIBLE);
                chargeLayout.setVisibility(View.VISIBLE);
                chargeEdit.setFocusable(true);
                chargeEdit.setFocusableInTouchMode(true);
                chargeEdit.requestFocus();
                im.showSoftInput(chargeEdit, 0);
                liveType = 1;
                break;
            case R.id.password:
                chargeLayout.setVisibility(View.GONE);
                lineDivider.setVisibility(View.VISIBLE);
                pwdLayout.setVisibility(View.VISIBLE);
                passwordEdit.setFocusable(true);
                passwordEdit.setFocusableInTouchMode(true);
                passwordEdit.requestFocus();
                im.showSoftInput(passwordEdit, 0);
                liveType = 2;
                break;
            case R.id.vip1:
                liveType = 3;
                pwdLayout.setVisibility(View.GONE);
                chargeLayout.setVisibility(View.GONE);
                lineDivider.setVisibility(View.GONE);
                try {
                    im.hideSoftInputFromWindow(ZhiboSettingActivity.this.getCurrentFocus().getWindowToken(), 0);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            case R.id.vip2:
                liveType = 4;
                pwdLayout.setVisibility(View.GONE);
                chargeLayout.setVisibility(View.GONE);
                lineDivider.setVisibility(View.GONE);
                try {
                    im.hideSoftInputFromWindow(ZhiboSettingActivity.this.getCurrentFocus().getWindowToken(), 0);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            case R.id.vip3:
                liveType = 5;
                pwdLayout.setVisibility(View.GONE);
                chargeLayout.setVisibility(View.GONE);
                lineDivider.setVisibility(View.GONE);
                try {
                    im.hideSoftInputFromWindow(ZhiboSettingActivity.this.getCurrentFocus().getWindowToken(), 0);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            case R.id.vip4:
                liveType = 6;
                pwdLayout.setVisibility(View.GONE);
                chargeLayout.setVisibility(View.GONE);
                lineDivider.setVisibility(View.GONE);
                try {
                    im.hideSoftInputFromWindow(ZhiboSettingActivity.this.getCurrentFocus().getWindowToken(), 0);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            case R.id.vip5:
                liveType = 7;
                pwdLayout.setVisibility(View.GONE);
                chargeLayout.setVisibility(View.GONE);
                lineDivider.setVisibility(View.GONE);
                try {
                    im.hideSoftInputFromWindow(ZhiboSettingActivity.this.getCurrentFocus().getWindowToken(), 0);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
        }
    }
}
